{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Manifold Learning\n",
    "\n",
    "Manifold learning finds a low-dimensional basis for describing high-dimensional data. Manifold learning is a popular approach to nonlinear dimensionality reduction. Algorithms for this task are based on the idea that the dimensionality of many data sets is only artificially high; though each data point consists of perhaps thousands of features, it may be described as a function of only a few underlying parameters. That is, the data points are actually samples from a low-dimensional manifold that is embedded in a high-dimensional space. Manifold learning algorithms attempt to uncover these parameters in order to find a low-dimensional representation of the data.\n",
    "\n",
    "Some prominent approaches are locally linear embedding (LLE), Hessian LLE, Laplacian eigenmaps, and LTSA. These techniques construct a low-dimensional data representation using a cost function that retains local properties of the data, and can be viewed as defining a graph-based kernel for Kernel PCA. More recently, techniques have been proposed that, instead of defining a fixed kernel, try to learn the kernel using semidefinite programming. The most prominent example of such a technique is maximum variance unfolding (MVU). The central idea of MVU is to exactly preserve all pairwise distances between nearest neighbors (in the inner product space), while maximizing the distances between points that are not nearest neighbors.\n",
    "\n",
    "An alternative approach to neighborhood preservation is through the minimization of a cost function that measures differences between distances in the input and output spaces. Important examples of such techniques include classical multidimensional scaling (which is identical to PCA), Isomap (which uses geodesic distances in the data space), diffusion maps (which uses diffusion distances in the data space), t-SNE (which minimizes the divergence between distributions over pairs of points), and curvilinear component analysis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import $ivy.`com.github.haifengl::smile-scala:4.0.0`\n",
    "import $ivy.`org.slf4j:slf4j-simple:2.0.16`  \n",
    "\n",
    "import scala.language.postfixOps\n",
    "import smile._\n",
    "import smile.math._\n",
    "import smile.math.distance._\n",
    "import smile.math.kernel._\n",
    "import smile.math.matrix._\n",
    "import smile.math.matrix.Matrix._\n",
    "import smile.math.rbf._\n",
    "import smile.stat.distribution._\n",
    "import smile.data._\n",
    "import smile.data.formula._\n",
    "import smile.data.measure._\n",
    "import smile.data.`type`._\n",
    "import smile.manifold._\n",
    "\n",
    "import java.awt.Color.{BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW}\n",
    "import smile.plot.swing.Palette.{DARK_RED, VIOLET_RED, DARK_GREEN, LIGHT_GREEN, PASTEL_GREEN, FOREST_GREEN, GRASS_GREEN, NAVY_BLUE, SLATE_BLUE, ROYAL_BLUE, CADET_BLUE, MIDNIGHT_BLUE, SKY_BLUE, STEEL_BLUE, DARK_BLUE, DARK_MAGENTA, DARK_CYAN, PURPLE, LIGHT_PURPLE, DARK_PURPLE, GOLD, BROWN, SALMON, TURQUOISE, BURGUNDY, PLUM}\n",
    "import smile.plot.swing._\n",
    "import smile.plot.show\n",
    "import smile.plot.Render._"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Isomap\n",
    "\n",
    "Isometric feature mapping (isomap) is a widely used low-dimensional embedding methods, where geodesic distances on a weighted graph are incorporated with the classical multidimensional scaling. Isomap is used for computing a quasi-isometric, low-dimensional embedding of a set of high-dimensional data points. Isomap is highly efficient and generally applicable to a broad range of data sources and dimensionalities.\n",
    "\n",
    "To be specific, the classical MDS performs low-dimensional embedding based on the pairwise distance between data points, which is generally measured using straight-line Euclidean distance. Isomap is distinguished by its use of the geodesic distance induced by a neighborhood graph embedded in the classical scaling. This is done to incorporate manifold structure in the resulting embedding. Isomap defines the geodesic distance to be the sum of edge weights along the shortest path between two nodes. The top n eigenvectors of the geodesic distance matrix, represent the coordinates in the new n-dimensional Euclidean space.\n",
    "```\n",
    "def isomap(data: Array[Array[Double]], k: Int, d: Int = 2, CIsomap: Boolean = true): IsoMap\n",
    "``` \n",
    "The connectivity of each data point in the neighborhood graph is defined as its nearest k Euclidean neighbors in the high-dimensional space. This step is vulnerable to \"short-circuit errors\" if k is too large with respect to the manifold structure or if noise in the data moves the points slightly off the manifold. Even a single short-circuit error can alter many entries in the geodesic distance matrix, which in turn can lead to a drastically different (and incorrect) low-dimensional embedding. Conversely, if k is too small, the neighborhood graph may become too sparse to approximate geodesic paths accurately.\n",
    "\n",
    "When the optional parameter CIsomap is true, the method performs C-Isomap that involves magnifying the regions of high density and shrink the regions of low density of data points in the manifold. Edge weights that are maximized in Multi-Dimensional Scaling(MDS) are modified, with everything else remaining unaffected.\n",
    "\n",
    "In the below example, we apply Isomap to the famous swiss roll data as shown above. This data set was created to test out various dimensionality reduction algorithms. The idea was to create several points in 2d, and then map them to 3d with some smooth function, and then to see what the algorithm would find when it mapped the points back to 2d. The data contains 20,000 samples. Because it is computational intensive to calculate the shortest path for all samples, the example uses only the first 2,000 samples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val swissroll = read.csv(\"../data/manifold/swissroll.txt\", header=false, delimiter=\"\\t\").toArray()\n",
    "show(plot(swissroll, '.', BLUE))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "we use `k = 7` for neighborhood graph. In the mapped 2d space, we also plot the connections between neighbor neighbors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import scala.jdk.CollectionConverters._\n",
    "\n",
    "val map = isomap(swissroll.slice(0, 2000), 7)\n",
    "val vertices = map.coordinates\n",
    "val edges = map.graph.getEdges().asScala.map(edge => Array(edge.v1, edge.v2)).toArray\n",
    "\n",
    "val canvas = wireframe(vertices, edges)\n",
    "canvas.setTitle(\"IsoMap\");\n",
    "show(canvas)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that Isomap produces strange holes like in a slice of Swiss cheese :). This issue can be solved by adding to Isomap a vector quantization step."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## LLE\n",
    "\n",
    "Locally Linear Embedding (LLE) has several advantages over Isomap, including faster optimization when implemented to take advantage of sparse matrix algorithms, and better results with many problems. LLE also begins by finding a set of the nearest neighbors of each point. It then computes a set of weights for each point that best describe the point as a linear combination of its neighbors. Finally, it uses an eigenvector-based optimization technique to find the low-dimensional embedding of points, such that each point is still described with the same linear combination of its neighbors. LLE tends to handle non-uniform sample densities poorly because there is no fixed unit to prevent the weights from drifting as various regions differ in sample densities.\n",
    "```\n",
    "def lle(data: Array[Array[Double]], k: Int, d: Int = 2): LLE\n",
    "``` "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val map = lle(swissroll.slice(0, 2000), 8)\n",
    "val vertices = map.coordinates\n",
    "val edges = map.graph.getEdges().asScala.map(edge => Array(edge.v1, edge.v2)).toArray\n",
    "\n",
    "val canvas = wireframe(vertices, edges)\n",
    "canvas.setTitle(\"LLE\");\n",
    "show(canvas)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Laplacian Eigenmap\n",
    "\n",
    "Using the notion of the Laplacian of the nearest neighbor adjacency graph, Laplacian Eigenmap computes a low dimensional representation of the dataset that optimally preserves local neighborhood information in a certain sense. The representation map generated by the algorithm may be viewed as a discrete approximation to a continuous map that naturally arises from the geometry of the manifold.\n",
    "```\n",
    "def laplacian(data: Array[Array[Double]], k: Int, d: Int = 2, t: Double = -1): LaplacianEigenmap\n",
    "``` \n",
    "where t is the smooth/width parameter of heat kernel `exp(-||x-y||2/t)`. Non-positive t means discrete weights.\n",
    "\n",
    "The locality preserving character of the Laplacian Eigenmap algorithm makes it relatively insensitive to outliers and noise. It is also not prone to \"short circuiting\" as only the local distances are used."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val map = laplacian(swissroll.slice(0, 1000), 10, 2, 25.0)\n",
    "val vertices = map.coordinates\n",
    "val edges = map.graph.getEdges().asScala.map(edge => Array(edge.v1, edge.v2)).toArray\n",
    "\n",
    "val canvas = wireframe(vertices, edges)\n",
    "canvas.setTitle(\"Laplacian Eigenmap\");\n",
    "show(canvas)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## t-SNE\n",
    "\n",
    "The t-distributed stochastic neighbor embedding (t-SNE) is a nonlinear dimensionality reduction technique that is particularly well suited for embedding high-dimensional data into a space of two or three dimensions, which can then be visualized in a scatter plot. Specifically, it models each high-dimensional object by a two- or three-dimensional point in such a way that similar objects are modeled by nearby points and dissimilar objects are modeled by distant points.\n",
    "```\n",
    "def tsne(X: Array[Array[Double]], d: Int = 2, perplexity: Double = 20.0, eta: Double = 200.0, iterations: Int = 1000): TSNE\n",
    "``` \n",
    "where X is input data, perplexity is the perplexity of the conditional distribution, eta the learning rate, and iterations is the number of iterations. If X is a square matrix, it is assumed to be the distance/dissimilarity matrix.\n",
    "\n",
    "The t-SNE on the MNIST data is as follows. Note that the input data is preprocessed using PCA to reduce the dimensionality to 50 before t-SNE is performed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "val x = read.csv(\"../data/mnist/mnist2500_X.txt\", header=false, delimiter=' ').toArray\n",
    "val y = read.csv(\"../data/mnist/mnist2500_labels.txt\", header=false, delimiter=' ').column(0).toIntArray\n",
    "val pc = smile.projection.pca(x)\n",
    "pc.setProjection(50)\n",
    "val x50 = pc.project(x)\n",
    "val sne = tsne(x50, 3, 20, 200, 1000)\n",
    "show(plot(sne.coordinates, y, '@'))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Scala (2.13)",
   "language": "scala",
   "name": "scala213"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".sc",
   "mimetype": "text/x-scala",
   "name": "scala",
   "nbconvert_exporter": "script",
   "version": "2.13.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
